package com.xyzh.stj.web.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xyzh.stj.web.entity.OrganizationEntity;
import com.xyzh.stj.web.dao.OrganizationMapper;

import com.xyzh.stj.web.entity.UserOrganizationEntity;
import com.xyzh.stj.web.service.OrganizationService;

import com.xyzh.stj.web.service.UserOrganizationService;
import com.xyzh.stj.web.vo.system.OrganizationPrems;
import com.xyzh.stj.web.vo.system.OrganizationVo;
import com.xyzh.application.base.service.BasicServiceImpl;
import com.xyzh.application.base.vo.AuthorUser;
import com.xyzh.application.common.util.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 组织机构 服务实现类
 * </p>
 *
 * @author @JZB
 * @since 2023-10-29
 */
@Service
public class OrganizationServiceImpl extends BasicServiceImpl<OrganizationMapper, OrganizationEntity> implements OrganizationService {



    @Autowired
    private UserOrganizationService userOrganizationService;


    @Value("#{applicationProperies.info.adminCode}")
    private String sysAdmin;


    @Override
    public List<OrganizationVo> selectAllCompany(OrganizationEntity organizationEntity) {
        LambdaQueryWrapper<OrganizationEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StrUtil.isNotEmpty(organizationEntity.getName()), OrganizationEntity::getName, organizationEntity.getName());
        List<OrganizationEntity> organizationEntities;
        if (queryWrapper.isEmptyOfWhere()) {
            organizationEntities = this.list(organizationEntity);
        } else {
            organizationEntities = this.list(queryWrapper);
        }
        return getChildOrgs("0", organizationEntities);
    }

    @Override
   public List<OrganizationPrems> selectOrganizationTree() {
        //当前用户
        List<OrganizationPrems> organizationPrems = new ArrayList<>();
        AuthorUser user = SecurityUtils.getAuthorUser();
        if (isAdminUser(user.getUsername())) {
            List<OrganizationEntity> orginOrgs = this.list();
            organizationPrems = orginOrgs.stream().map(d -> {
                OrganizationPrems prem = new OrganizationPrems();
                BeanUtils.copyProperties(d, prem);
                prem.setHasPrems(true);
                return prem;
            }).collect(Collectors.toList());
        } else {
            //他的组织
            List<OrganizationEntity> organizationEntities = this.getBaseMapper().getOrganizationsByUser(user.getId());
          if(CollUtil.isEmpty(organizationEntities)){
              return new ArrayList<>();
          }
            //他的上级组织
            List<OrganizationPrems> parentOrgs = this.getBaseMapper().getParentOrgsBySubsWithPrems(organizationEntities, false);
            //他的下级组织

            List<OrganizationPrems> subOrgs = this.getBaseMapper().getSubOrgsByParentsWithPrems(organizationEntities, true);
            parentOrgs.addAll(subOrgs);
            organizationPrems = parentOrgs.stream().distinct().collect(Collectors.toList());
        }
        return getChildOrgsPrems("0", organizationPrems);

    }

    @Override
    public List<OrganizationEntity> getOrganizations(String userid) {
        return this.getBaseMapper().getOrganizationsByUser(userid);

    }

    @Override
    public List<String> getSubOrgidsByParent(List<OrganizationEntity> organizationEntities) {
        if(CollUtil.isEmpty(organizationEntities)){
            return new ArrayList<>();
        }
        return this.getBaseMapper().getSubOrgidsByParents(organizationEntities);
    }

    @Override
    public List<String> getSubOrgidsByParentId(String parentId) {
        return this.getBaseMapper().getSubOrgidsByParentId(parentId);
    }

    @Override
    public boolean save(OrganizationEntity entity) {
        if (StrUtil.isEmpty(entity.getPid())) {
            entity.setPid("0");
        }
        if (entity.getSortkey() == 0) {
            entity.setSortkey(this.queryMaxSortkey("organization"));
        }
        return super.save(entity);
    }

    public List<OrganizationPrems> getChildOrgsPrems(String pid, List<OrganizationPrems> rights) {
        List<OrganizationPrems> menuRights = new ArrayList<>();
        for (OrganizationPrems right : rights) {
            if (pid.equals(right.getPid())) {//判断传入的父id是否等于自身的，如果是，就说明自己是子节点
                menuRights.add(right);
            }
        }
        for (OrganizationPrems map : menuRights) {//遍历子节点，继续递归判断每个子节点是否还含有子节点
            List<OrganizationPrems> childList = getChildOrgsPrems(map.getId(), rights);
            map.setChildren(childList);
        }
        return menuRights;
    }

    public List<OrganizationVo> getChildOrgs(String pid, List<OrganizationEntity> rights) {
        List<OrganizationVo> menuRights = new ArrayList<>();
        for (OrganizationEntity right : rights) {
            if (pid.equals(right.getPid())) {//判断传入的父id是否等于自身的，如果是，就说明自己是子节点
                OrganizationVo menu = new OrganizationVo();
                BeanUtils.copyProperties(right, menu);
                menuRights.add(menu);
            }
        }
        for (OrganizationVo map : menuRights) {//遍历子节点，继续递归判断每个子节点是否还含有子节点
            List<OrganizationVo> childList = getChildOrgs(map.getId(), rights);
            map.setChildren(childList);
        }
        return menuRights;
    }


    private boolean isAdminUser(String CurrentUser) {
        return sysAdmin.equals(CurrentUser);
    }
}
